using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace SqlTools.SchemaReader
{
	public class ForeignKey : DbObject
	{
		private Table _referenceTable = null;
		private Column _referenceColumn = null;

		private Table _foreignKeyTable = null;
		private Column _foreignKeyColumn = null;

		public ForeignKey() : this("", 0) { }

		public ForeignKey(string name, int id)
			: base(name, id)
		{

		}

		public Table ReferenceTable
		{
			get { return _referenceTable; }
			internal set { _referenceTable = value; }
		}

		public Column ReferenceColumn
		{
			get { return _referenceColumn; }
			internal set { _referenceColumn = value; }
		}

		public Table ForeignKeyTable
		{
			get { return _foreignKeyTable; }
			internal set { _foreignKeyTable = value; }
		}

		public Column ForeignKeyColumn
		{
			get { return _foreignKeyColumn; }
			internal set { _foreignKeyColumn = value; }
		}

		public override DbObjectType Type
		{
			get { return DbObjectType.ForeignKey; }
		}

		public override XmlElement CreateXmlElement(XmlDocument doc, XmlNode parent)
		{
			XmlElement el = base.CreateXmlElement(doc, parent);

			if ( _referenceTable != null )
				el.Attributes.Append(doc.CreateAttribute("referencetableid")).Value = _referenceTable.ID.ToString();
			if ( _referenceColumn != null )
				el.Attributes.Append(doc.CreateAttribute("referencecolumnid")).Value = _referenceColumn.ID.ToString();

			if ( _foreignKeyTable != null )
				el.Attributes.Append(doc.CreateAttribute("foreignkeytableid")).Value = _foreignKeyTable.ID.ToString();
			if ( _foreignKeyColumn != null )
				el.Attributes.Append(doc.CreateAttribute("foreignkeycolumnid")).Value = _foreignKeyColumn.ID.ToString();

			return el;
		}

		public override void LoadXml(XmlElement el, Database db)
		{
			base.LoadXml(el, db);

			string ivalue = "";
			int id = 0;

			ivalue = el.GetAttribute("referencetableid");
			if ( int.TryParse(ivalue, out id) )
			{
				_referenceTable = db.Tables.RetrieveByID(id);

				if ( _referenceTable != null )
				{
					//_referenceTable.ForeignKeys.Add(this);

					ivalue = el.GetAttribute("referencecolumnid");
					if ( int.TryParse(ivalue, out id) )
					{
						_referenceColumn = _referenceTable.Columns.RetrieveByID(id);
					}
				}
			}

			ivalue = el.GetAttribute("foreignkeytableid");
			if ( int.TryParse(ivalue, out id) )
			{
				_foreignKeyTable = db.Tables.RetrieveByID(id);

				if ( _foreignKeyTable != null )
				{
					// don't add it twice
					//if ( _foreignKeyTable != _referenceTable )
					_foreignKeyTable.ForeignKeys.Add(this);

					ivalue = el.GetAttribute("foreignkeycolumnid");
					if ( int.TryParse(ivalue, out id) )
					{
						_foreignKeyColumn = _foreignKeyTable.Columns.RetrieveByID(id);
					}
				}
			}
		}
	}
}
